<template>
  <div class="container">
    <h1>{{id? '编辑':'新增'}}友链</h1>
    <el-form :model="model" @submit.native.prevent="save">
      <el-form-item label="名字">
        <el-input v-model="model.name"></el-input>
      </el-form-item>

      <el-form-item label="链接">
        <el-input v-model="model.url"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit">{{id? '保存':'新增'}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      model: {},
    };
  },
  methods: {
    async save() {
      // 新增友链
      if (!this.id) {
        let res = await this.$http.post("/friendship", this.model);
        this.$message({
          type: "success",
          message: "新增友链成功",
        });
        this.$router.push("/friendships/list");
        // 编辑友链
      } else {
        let res = await this.$http.put(`/friendship/${this.id}`, this.model);
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.$router.push("/friendships/list");
      }
    },
    // 获取编辑友链初始数据
    async fetch() {
      const res = await this.$http.get(`/friendship/${this.id}`);
      this.model = res.data;
    },
  },
  created() {
    this.id && this.fetch();
  },
};
</script>

<style></style>